import java.io.IOException;
import java.io.RandomAccessFile;

//Class containing operations of datatype r8
public class r8 extends datatype implements read,write{

	public void write(String data, int length) throws IOException
	{
		//System.out.println("r8 write called");
		RandomAccessFile fi= new RandomAccessFile(heap.f,"rw");
		fi.seek(heap.f.length());
		double b=Double.parseDouble(data);
		fi.writeDouble(b);
		fi.close();
	}
	public String read(int length) throws IOException
	{
		String str;
		RandomAccessFile fip= new RandomAccessFile(heap.f, "rw");
		fip.seek(heap.readpointer);
		str=""+fip.readDouble();
		heap.readpointer+=8;
		fip.close();
		return str;
	}
	public int compares(String value1,String value2) throws IOException
	{
		int result=0;
		double record1=Double.parseDouble(value1);
		double record2=Double.parseDouble(value2);
		result = record1>record2?1:record1<record2?2:0;
		return result;

	}
	public Object convert(String str)
	{
		double d = Double.parseDouble(str);
		return d;
	}
	public byte[] returnPrimitive(String str)
	{
		double d = Double.parseDouble(str);
		long l = Double.doubleToRawLongBits(d);
		return new byte[] {
				
				(byte)((l >> 56) & 0xff),
				(byte)((l >> 48) & 0xff),
				(byte)((l >> 40) & 0xff),
				(byte)((l >> 32) & 0xff),
				(byte)((l >> 24) & 0xff),
				(byte)((l >> 16) & 0xff),
				(byte)((l >> 8) & 0xff),
				(byte)((l >> 0) & 0xff),
		};
		
	}
	public Object getPrimitive(byte [] data)
	{
		if (data == null || data.length != 8) return 0x0;
		// ---------- simple:
		return Double.longBitsToDouble(toLong(data));
	}
	
	public static long toLong(byte[] data) {
		if (data == null || data.length != 8) return 0x0;
		// ----------
		return (long)(
		// (Below) convert to longs before shift because digits
		// are lost with ints beyond the 32-bit limit
		(long)(0xff & data[0]) << 56 |
		(long)(0xff & data[1]) << 48 |
		(long)(0xff & data[2]) << 40 |
		(long)(0xff & data[3]) << 32 |
		(long)(0xff & data[4]) << 24 |
		(long)(0xff & data[5]) << 16 |
		(long)(0xff & data[6]) << 8 |
		(long)(0xff & data[7]) << 0
		);
		}
}
